﻿using Dt261.Model;
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dt261.db
{
    class ResultEntryDb
    {
        private readonly SQLiteConnection connection;

        public ResultEntryDb(string dbPath)
        {
            connection = new SQLiteConnection(dbPath);
            connection.CreateTable<ResultEntry>();
        }
            
        public int AddResultEntry(ResultEntry m)
        {

            return connection.Insert(new ResultEntry()
            {
                Uid = m.Uid,
                PointState = m.PointState,
                PointType = m.PointType,
                ValueX = m.ValueX,
                ValueY = m.ValueY,
                IsUserResp = m.IsUserResp,
                TestToneType = m.TestToneType,
                TestToneTime = m.TestToneTime,
                MarkType = m.MarkType,
                YanbiType = m.YanbiType,
                DataSetId = m.DataSetId,

    });
        }

        public int UpdateResultEntry(ResultEntry m)
        {

            IList<ResultEntry> list = connection.Query<ResultEntry>("select * from ResultEntry where id = ?", m.Id);

            if (list.Count() > 0)
            {
                return connection.Update(m);
            }
            else
            {
                return this.AddResultEntry(m);
            }
        }

        public IList<ResultEntry> GetResultEntrys()
            => connection.Table<ResultEntry>().ToList();

        public IList<ResultEntry> GetResultEntryByUid(string uid)
        {
            IList<ResultEntry> list = connection.Query<ResultEntry>("select * from ResultEntry where uid = ?", uid);

            return list;
        }

        public IList<ResultEntry> GetResultEntryById(int id)
        {
            IList<ResultEntry> list = connection.Query<ResultEntry>("select * from ResultEntry where id = ?", id);

            return list;
        }

        public IList<ResultEntry> GetResultEntrysByDataSetId(string did)
        {
            IList<ResultEntry> list = connection.Query<ResultEntry>("select * from ResultEntry where DataSetId = ?", did);

            return list;
        }

        public ResultEntry GetOneResultEntryByUid(string uid)
        {
            IList<ResultEntry> list = connection.Query<ResultEntry>("select * from ResultEntry where uid = ?", uid);

            return list.Count() > 0 ? list[0] : null;
        }

        public ResultEntry GetOneResultEntryById(int id)
        {
            IList<ResultEntry> list = connection.Query<ResultEntry>("select * from ResultEntry where id = ?", id);

            return list.Count() > 0 ? list[0] : null;
        }

        public int DeleteUser(ResultEntry m)
        {
            return connection.Delete(m);
        }
    }
}
